# Create your views here.
import md5
import urllib,urllib2, httplib 
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse
from django.utils import simplejson
from django.contrib.auth.models import User

from online_shop.products.models import product_favourite
from online_shop.orders.models import address
from online_shop.products.views import get_recent_viewed_object
from online_shop.users.forms import *
from online_shop.cart import cart
from online_shop.orders.models import address,orders,order_details, order_status

def show_cart(request):
    amount = cart.cart_distinct_item_count(request)
    cart_items = cart.get_cart_items(request)
    cart_subtotal = cart.cart_subtotal(request)
    if request.user.is_authenticated():
        user = get_object_or_404(User, username=request.user.username)
        favourite_products = user.favourite_user.all()
        variables = RequestContext(request,{
            'favourite_products': favourite_products,
            'amount': amount,
            'cart_items': cart_items,
            'cart_subtotal': cart_subtotal,
            'recent_viewed': get_recent_viewed_object(request),
        })
    else:
        variables = RequestContext(request,{
            'amount': amount,
            'cart_items': cart_items,
            'cart_subtotal': cart_subtotal,
            'recent_viewed': get_recent_viewed_object(request),
        })
    return render_to_response(
        'shopping cart/cart_display.html',
        variables,
    )
    
def modify_cart(request):
    modify_result = {}
    if request.method == 'POST':
        postdata = request.POST.copy()
        if postdata['submit'] == 'Remove':
            cart.remove_from_cart(request)
        if postdata['submit'] == 'Update':
            cart_item = cart.update_cart(request)
            if cart_item:
                total = cart_item.total()
                modify_result['single_item_total'] = total
            else:
                modify_result['single_item_total'] = 0
    amount = cart.cart_distinct_item_count(request)
    cart_subtotal = cart.cart_subtotal(request)
    modify_result['all_items_total'] = cart_subtotal
    modify_result['items_amount'] = amount
    return HttpResponse(simplejson.dumps(modify_result), mimetype='application/json')

def cart_check_address(request):
    if request.user.is_authenticated():
        user = get_object_or_404(User, username=request.user.username)
        addresses = user.address_set.all()
        form = DeliverAddress()
        #addresses =  address.objects.filter(user=user)
        variables = RequestContext(request,{
            'my_addresses': addresses,
            'form': form
        })
    else:
        return HttpResponseRedirect('/login/')
    return render_to_response(
        'shopping cart/check_address_page.html',
        variables,
    )
    
def cart_confirmation(request,address_id):
    if request.user.is_authenticated():
        user = get_object_or_404(User, username=request.user.username)
        my_address = address.objects.get(id=address_id)
        amount = cart.cart_distinct_item_count(request)
        cart_items = cart.get_cart_items(request)
        cart_subtotal = cart.cart_subtotal(request)
        #checksumstr = "pid=%s&sid=%s&amount=%s&token=%s"%(address_id, "zxhwd2008", cart_subtotal, "7a74e5575157afd5be80734c5ee261c5")
        #m = md5.new(checksumstr)
        #checksum = m.hexdigest()
        variables = RequestContext(request,{
            'user': user,
            'my_address': my_address,
            'amount': amount,
            'cart_items': cart_items,
            'cart_subtotal': cart_subtotal,
            'recent_viewed': get_recent_viewed_object(request),
            #'checksum': checksum,
        })
        
    else:
        return HttpResponseRedirect('/login/')
    return render_to_response(
        'shopping cart/confirmation_page.html',
        variables,
    )

def cart_payment(request):
    result = {}
    if request.user.is_authenticated():
        postdata = request.POST.copy()
        my_address_id = postdata.get('address_id',1)
        cart_items = cart.get_cart_items(request)
        cart_subtotal = cart.cart_subtotal(request)
        user = User.objects.get(username=request.user.username)
        my_order_status = get_object_or_404(order_status, type='UNPAID')
        my_address = get_object_or_404(address, id=my_address_id)
        my_order = orders()
        my_order.iduser = user
        my_order.status = my_order_status     #SUBMITTED = 1   PROCESSED = 2    SHIPPED = 3    ARRIVED = 4    CANCELLED = 5
        my_order.idaddress = my_address
        my_order.save()
        for cart_item in cart_items:
            my_order_details = order_details()
            my_order_details.idorder = my_order
            my_order_details.idproduct = cart_item.product
            my_order_details.count = cart_item.quantity
            my_order_details.unit_price = cart_item.price()
            my_order_details.save()
        pid = my_order.id
        checksumstr = "pid=%s&sid=%s&amount=%s&token=%s"%(pid, "zxhwd2008", cart_subtotal, "7a74e5575157afd5be80734c5ee261c5")
        m = md5.new(checksumstr)
        checksum = m.hexdigest()
        result['order_id'] = pid
        result['checksum'] = checksum
    else:
        return HttpResponseRedirect('/login/')
    return HttpResponse(simplejson.dumps(result), mimetype='application/json')
